# consumers.py
import json
import time

from asgiref.sync import sync_to_async
from django_q.tasks import result

from channels.generic.websocket import AsyncWebsocketConsumer
import json

async_result = sync_to_async(result, thread_sensitive=True)


class FileUploadStatus(AsyncWebsocketConsumer):
    async def connect(self):
        # 当客户端请求连接时调用
        self.room_group_name = 'file-upload-status'

        # 将频道加入组
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # 当连接关闭时调用
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        # 当收到消息时调用
        print(f"接收到数据:{text_data}")

        self.async_id = text_data
        start_time = time.time()
        while time.time() - start_time <= 20:
            value = await async_result(self.async_id, wait=2)
            if value is not None:
                await self.group_send_message(value)
                return
        await self.group_send_message("error:timeout")

    async def group_send_message(self, data, type='chat_message'):
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': type,
                "file": data,
                "ws": self.async_id
            }
        )

    async def chat_message(self, event):
        # 从组中接收消息并将其发送给WebSocket
        message = event['file']

        await self.send(text_data=json.dumps({
            'type': 'chat_message',
            'file': message,
            "ws": self.async_id
        }))
